use std::{collections::HashMap, env};

use axum::http::Response;
use openssl::{cipher::Cipher, symm};

// 模拟解密操作
fn decrypt_data(data: &str) -> Result<String, String> {
    dotenv::dotenv().ok();
    let result_object: serde_json::Value = match serde_json::from_str(data) {
        Ok(v) => v,
        Err(_) => return Err("无法解析JSON".into()),
    };

    let resource = result_object["resource"].as_object().unwrap();
    let ciphertext = resource["ciphertext"].as_str().unwrap_or_default();
    let nonce = resource["nonce"].as_str().unwrap_or_default();
    let associated_data = resource["associated_data"].as_str().unwrap_or_default();

    let api_v3_key = env::var("wechat.apiV3Key").unwrap();
    let aes_util = AesUtil::new(api_v3_key.as_bytes().to_vec()); // 使用实际的 apiV3Key
    aes_util.decrypt_to_string(
        associated_data.as_bytes(),
        nonce.as_bytes(),
        ciphertext.as_bytes(),
    )
}

// 给微信响应
fn response_to_weixin(response: &mut Response) {
    response
}

pub async fn pay_success_notify(body: String) {
    tracing::info!("支付成功回调：{}", body);
    let plain_txt = match decrypt_data(&body) {
        Ok(txt) => txt,
        Err(e) => todo!(),
    };
}

// 模拟 AES
struct AesUtil {
    api_v3_key: Vec<u8>,
}

impl AesUtil {
    fn new(api_v3_key: Vec<u8>) -> Self {
        AesUtil { api_v3_key }
    }

    fn decrypt_to_string(
        &self,
        associated_data: &[u8],
        nonce: &[u8],
        ciphertext: &[u8],
    ) -> Result<String, String> {
        // 解密操作
        let cipher = Cipher::aes_256_gcm();

        let decrypted_data = match symm::decrypt(
            cipher,
            &self.api_v3_key,
            Some(nonce),
            associated_data,
            // ciphertext,
        ) {
            Ok(data) => data,
            Err(e) => return Err(format!("解密失败: {}", e)),
        };

        String::from_utf8(decrypted_data).map_err(|e| format!("解密后转换为字符串失败: {}", e))
    }
}
